<template>
    <div class="background"></div>
    <div class="chat">
      <div class="navigation">
          <span @click="Tomain">主页</span>
          <span @click="Tocart">购物车</span>
          <span @click="Touser">个人中心</span>
      </div>
      <h4 v-if="activeUser" class="ti">{{ activeUser.username }}</h4>
      <h4 v-else-if="!activeUser" class="ti">{{ noActiveUserMessage }}</h4>
      <div class="zhu">
    <div class="chat-list">
      <div class="search-bar">
        <h2>管理员</h2>
        <div class="user-box"  @click="startConversation(admin)">
          <li>
            {{ admin.username }}
         </li>
       </div>
      </div>
      <div class="search-bar">
        <h2>消息列表</h2>
        <input type="text" v-model="searchQuery" placeholder="Search for a user..." @input="filterUsers">
      </div>
      <ul>
        <div class="user-box" v-for="user in filteredUsers" :key="user.id" @click="startConversation(user)">
          <li>
            {{ user.username }}
         </li>
       </div>
      </ul>
    </div>
      <div v-if="activeUser">
        <div class="chat-container">
          <div v-for="message in conversation" :key="message.id" class="chat-message" :class="{'message-sent': message.from == this.username, 'message-received': message.from == activeUser}">
            <div class="chat-message-content">
              <div class="chat-text">{{ message.text }}</div>
            </div>
            <span class="chat-name">{{ message.from }}</span>
            </div>
        </div>
      </div>
      <div v-else-if="!activeUser">
        <div class="chat-container"></div>
      </div>
      </div>
      <div class="message-input-area" v-if="activeUser">
      <input type="text" v-model="newMessage" @click="send" @keyup.enter="sendMessage" placeholder="Type a message..." class="message-input"/>
        <button @click="sendMessage" class="send-button">发送</button>
    </div>
    <div class="message-input-area" v-else-if="!activeUser">
      <input type="text" v-model="newMessage" @click="send" @keyup.enter="sendMessage" placeholder="Type a message..." class="message-input"/>
        <button @click="sendMessage" class="send-button">发送</button>
    </div>
      </div>
    
  </template>
  
  <script>
  import { client } from 'webstomp-client';
  import { globalState } from '../global.js';
  import axios from 'axios'; 
  export default {
    data() {
      return {
        users: [],
        ws:null,
        activeUser :"xiaowang",
        conversation: [], // 从本地存储中获取聊天记录
        newMessage: '',
        searchQuery: '',
        username:'',
        admin: {username: 'admin'},
        filteredUsers: [],
        latestMessages: {}, // 用于存储最新消息
        noActiveUserMessage: '请选择一个聊天对象开始对话',
        messageIds: {} // 用于跟踪消息ID，避免重复显示
      };
    }, 
    created() {
      this.fetchUsername();
      console.log('Filtered users:', this.filteredUsers);
      this.filterUsers(); // 添加新的方法调用以获取用户数据
    },
    computed: {
    // 新增一个计算属性，用于处理聊天记录的排序
    sortedConversation() {
      return this.conversation.slice().sort((a, b) => a.timestamp - b.timestamp);
    },
  },
  beforeDestroy() {
    if (client) {
      client.close()
    }
  },
    methods: {
      hasSentMessages(user) {
      const conversationKey = `conversation-${this.username}-${user.username}`;
      const storedMessages = localStorage.getItem(conversationKey);
      return !!storedMessages && JSON.parse(storedMessages).length > 0;
    },
      Tomain() {
        this.$router.push('/mainpage');
      },
      Tocart() {
        this.$router.push('/cart');
      },
      Touser() {
        this.$router.push('/userpage');
      },
      async filterUsers() {
    try {
      // 请求所有用户的列表
      const response = await axios.get('http://localhost:8080/getusername'); 
      console.log('Received users:', response.data);
      this.users = response.data;
      // 如果有搜索查询，则应用过滤
      if (this.searchQuery) {
        this.filteredUsers = this.users.filter(user => 
          user.username.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      } else {
        // 如果没有搜索查询，则显示所有有聊天记录的用户
        this.filteredUsers = this.users.filter(user => 
          this.hasSentMessages(user)
        );
        // 在过滤之后，确保管理员始终显示
        this.filteredUsers = this.filteredUsers;
      }
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  },
  handleReconnect() {
      // 这个方法在重新连接后调用，用于处理离线消息
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ action: 'reconnect' }));
        this.$nextTick(() => {
          // DOM 更新后，确保聊天记录被正确排序
          this.conversation.sort((a, b) => a.timestamp - b.timestamp);
        });
      }
    },
  fetchUsername() {
    this.username = globalState.username || '';
  },
  wsOnMessage(event) {
      const data = JSON.parse(event.data);
      if (data.type === 'message') {
          // 确保消息是发给当前用户的
          if (data.to === this.username) {
              this.addMessage(data);
          }
      } else if (data.type === 'reconnect') {
          // 处理离线消息
          data.messages.forEach(msg => {
              if (msg.to === this.username) {
                  this.addMessage(msg);
              }
          });
          this.$nextTick(() => {
              // DOM 更新后，确保聊天记录被正确排序
              this.conversation.sort((a, b) => a.timestamp - b.timestamp);
          });
      }
  },
  connectWebSocket() {
    this.ws = new WebSocket(`ws://localhost:8080/websocket/${this.username}`);
  
    this.ws.onopen = () => {
    console.log('Connected to WebSocket server');
    this.ws.send(JSON.stringify({ action: 'reconnect' }));
  };
  
    this.ws.onmessage = this.wsOnMessage.bind(this);
  
    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      // 重连逻辑
      setTimeout(() => {
        this.connectWebSocket();
      }, 5000);
    };
  
    this.ws.onclose = () => {
      console.log('Disconnected from WebSocket server');
      // 尝试重新连接
      setTimeout(() => {
        this.connectWebSocket();
      }, 5000);
    };
  },
      startConversation(user) {
  this.activeUser = user;
  const conversationKey = `conversation-${this.username}-${user.username}`;
  const storedMessages = localStorage.getItem(conversationKey);
  if (storedMessages) {
    this.conversation = JSON.parse(storedMessages);
  } else {
    this.conversation = [];
  }
  },
      sendMessage() {
  if (this.newMessage.trim()) {
    if (this.ws.readyState === WebSocket.OPEN) {
      const messageId = Date.now(); // 生成一个唯一的消息ID
      this.messageIds[messageId] = true; // 标记消息ID已使用
      
      // 构建消息对象并发送
      const message = {
        text: this.newMessage,
        from: this.username,
        to: this.activeUser.username, 
        id: messageId
      };
      
      this.ws.send(JSON.stringify(message));
      
      // 清空输入框
      this.newMessage = '';
      
      // 添加消息到本地存储和conversation数组
      this.addMessage(message);
    } else {
      // 存储消息以待重连后发送
      const messageId = Date.now();
      const message = {
        text: this.newMessage,
        from: this.username,
        to: this.activeUser ? this.activeUser.username : '',
        id: messageId
      };
      // 存储消息到localStorage
      let offlineMessages = JSON.parse(localStorage.getItem('offlineMessages')) || [];
      offlineMessages.push(message);
      localStorage.setItem('offlineMessages', JSON.stringify(offlineMessages));
    }
  }
  },
  addMessage(message) {
      message.timestamp = Date.now();
      // 首先检查是否已经存在相同ID的消息，以避免重复
      const existingMessage = this.conversation.find(m => m.id === message.id);
      if (!existingMessage) {
        // 如果不存在，则添加到conversation数组
        this.conversation.push(message);
        // 保存到localStorage前，确保message有timestamp字段
        if (!message.timestamp) message.timestamp = Date.now();
        const conversationKey = `conversation-${this.username}-${this.activeUser.username}`;
        localStorage.setItem(conversationKey, JSON.stringify(this.conversation));
        
        // DOM 更新后，确保聊天记录被正确排序
        this.$nextTick(() => {
          this.conversation.sort((a, b) => a.timestamp - b.timestamp);
        });
      }
    },
    loadMessages() {
      if (this.activeUser) {
        const conversationKey = `conversation-${this.username}-${this.activeUser.username}`;
        const storedMessages = localStorage.getItem(conversationKey);
        if (storedMessages) {
          this.conversation = JSON.parse(storedMessages).map(msg => ({...msg, timestamp: msg.timestamp || Date.now()}));
        } else {
          this.conversation = [];
        }
      }
    },
    loadOfflineMessages() {
  const offlineMessages = JSON.parse(localStorage.getItem('offlineMessages')) || [];
  offlineMessages.forEach(message => this.addMessage(message));
  localStorage.removeItem('offlineMessages'); // 清除离线消息列表
  }
    },
    watch: {
    // 监听activeUser变化，当切换用户时加载聊天记录
    activeUser: {
      immediate: true,
      handler(newValue) {
        if (newValue) {
          this.loadMessages();
          this.$nextTick(() => {
            this.conversation.sort((a, b) => a.timestamp - b.timestamp);
          });
        }
      },
    },
  },
  mounted() {
    this.username = globalState.username || ''; // Ensure username is set even if fetchUsername fails
    if (this.username) {
      this.connectWebSocket();
    }
    this.filteredUsers = this.users.slice();
    this.$nextTick(() => {
    this.loadOfflineMessages();
  });
  },
  }
  </script>
  
  <style scoped>
  .user-box {
    margin: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .user-box li {
    list-style-type: none;
  }
  
  .chat {
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    background-color: #fff;
    width: 100vw; /* 占据整个视口宽度 */
    height: 100vh; /* 占据整个视口高度 */
    background-image: url('../assets/img/mainpage.jpg');
    background-size: cover;
    background-position: center;
    background-color: rgba(41, 18, 192, 0.5); /* 设置背景颜色的透明度 */
    opacity: 0.95;
  }
  
  .zhu {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
  }
  
  /* 消息列表部分 */
  .chat-list {
    width: 220px;
    background-color: #bdbcbc;
    border-right: 1px solid #4e4e4e;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 160px); /* 减去顶部导航的高度或其他固定元素的高度 */
  }
  
  /* 消息列表部分 */
  .chat-list ul {
    overflow-y: auto; /* 添加垂直滚动条 */
    max-height: calc(100vh - 160px); /* 设置最大高度，减去顶部导航的高度或其他固定元素的高度 */
  }
  
  /* 管理员标题部分 */
  .search-bar {
    position: sticky;
    top: 0;
    z-index: 100; /* 确保它在其他元素之上 */
    background-color: #bcbcbd; /* 确保滚动时背景可见 */
  }
  
  
  /* 聊天窗口部分 */
  .chat-container {
    background-color: #f1f1f1;
    padding: 20px;
    overflow-y: auto; /* 添加滚动条 */
    display: flex;
    flex-direction: column;
    height: calc(100vh - 200px); /* 减去顶部导航的高度或其他固定元素的高度 */
    width: 500px;
  }
  
  .chat h4 {
    text-align: center;
    color: #4c4c4c;
  }
  
  /* 聊天消息样式 */
  .chat-message {
    display: flex;
    margin-bottom: 10px;
  }
  
  .chat-message-content {
    max-width: 75%;
    padding: 10px;
    border-radius: 5px;
    position: relative;
  }
  
  .message-sent {
    align-self: flex-end;
  }
  
  .message-received {
    align-self: flex-start;
    flex-direction: row-reverse;
  
  }
  
  .message-sent .chat-message-content {
    background-color: #dcf8c6;
    align-self: flex-end;
  }
  
  .message-received .chat-message-content {
    background-color: #fff;
    align-self: flex-start;
  }
  
  /* 气泡箭头 */
  .message-sent::before,
  .message-received::before {
    content: "";
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    border-style: solid;
    border-width: 10px;
  }
  
  .message-sent::before {
    right: -20px;
    border-color: transparent #dcf8c6 transparent transparent;
  }
  
  .message-received::before {
    left: -20px;
    border-color: transparent transparent transparent #fff;
  }
  
  /* 消息发送者的用户名 */
  .chat-name {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  
  /* 消息文本 */
  .chat-text {
    font-size: 16px;
    color: #333;
  }
  
  /* 输入框固定在底部 */
  .message-input {
    width: 650px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 25px;
    margin-top: auto; /* 推到底部 */
  }
  
  /* 发送按钮样式 */
  .send-button {
    padding: 10px;
    border: none;
    border-radius: 25px;
    width: 100px;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    margin-left: 5px;
  }
  
  .message-input-area {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    justify-content: center; /* 水平居中 */
  }
  
  .background {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-image: url('../assets/img/mainpage.jpg');
    background-size: cover;
    background-position: center;
    z-index: -1;
  }
  
  .navigation {
    display: flex;
    gap: 20px; /* 调整间距 */
    font-size: 30px;
    width: 95%;
    align-items: center;
    padding: 10px 20px;
    position: sticky;
    top: 0;
    z-index: 1000;
  }
  
  .navigation span {
    cursor: pointer;
    transition: color 0.3s;
    color: #ae08cf; /* 初始颜色 */
  }
  
  .navigation span:hover {
    color: red;
  }
  </style>